package com.zx.map.service.impl;

import com.zx.map.dao.AgentInfoDao;
import com.zx.map.dao.MerchantInfoDao;
import com.zx.map.dao.model.AgentInfo;
import com.zx.map.dao.model.AgentInfoExample;
import com.zx.map.service.AgentInfoService;
import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.domain.AgentInfoDomain;
import com.zx.map.service.domain.agent.TransAgentDomain;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.AgentSettleCardInfoModel;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.utils.CommonResponseUtils;
import com.zx.map.utils.MyBeanUtils;
import com.zx.map.utils.SUConstants;
import com.zx.platform.service.OperatorInfoService;
import com.zx.platform.service.model.OperatorInfoModel;
import com.zx.platform.service.model.OperatorRolesModel;
import com.zx.platform.utils.DesUtil;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 14-3-1 Time: 上午11:07 To
 * change this template use File | Settings | File Templates.
 */
@Service("agentInfoService")
public class AgentInfoServiceImpl implements AgentInfoService {
	private static Logger log = Logger.getLogger(AgentInfoServiceImpl.class);
	@Autowired
	private AgentInfoDao agentInfoDao;

	@Autowired
	private MerchantInfoDao merchantInfoDao;
	@Autowired
	private MerchantInfoService merchantInfoService;
	@Autowired
	private OperatorInfoService operatorInfoService;

	/**
	 * 得到所有数据列表
	 */
	public List getAllList() throws DataAccessException {

		List<AgentInfo> list = agentInfoDao.getListByExample(null);
		List<AgentInfoModel> modelList = MyBeanUtils.map(list, AgentInfoModel.class);
		return modelList;
	}

	/**
	 * 根据单Key查找Model
	 */
	public AgentInfoModel getModelByKey(String key) throws DataAccessException {
		AgentInfo o = agentInfoDao.selectByPrimaryKey(key);
		AgentInfoModel model = new AgentInfoModel();
		if (o != null) {
			BeanUtils.copyProperties(o, model);
		}
		return model;
	}


	/**
	 * 分页查询
	 *
	 * @param domain
	 * @return
	 * @throws DataAccessException
	 */
	public Map getPageByDomain(AgentInfoModel curAgentInfoModel, AgentInfoDomain domain)
			throws DataAccessException {
		Map<String, Object> map = new HashMap<String, Object>();
		AgentInfoModel agentInfoModel = new AgentInfoModel();
		agentInfoModel = MyBeanUtils.map(domain, AgentInfoModel.class);
		AgentInfoExample example = initAgentInfoExample(curAgentInfoModel, agentInfoModel);
		int pageBegin = (domain.getPageNum() - 1) * domain.getPageSize();
		List<AgentInfo> list = agentInfoDao.getPageByExample(domain.getPageSize(), pageBegin, example);

		List<AgentInfoModel> menuModelList = MyBeanUtils.map(list, AgentInfoModel.class);
		int count = agentInfoDao.countByExample(example);
		map.put("count", count);
		map.put("list", menuModelList);
		return map;
	}

	/**
	 * 意愿代理分页查询
	 *
	 * @param domain
	 * @return
	 * @throws DataAccessException
	 */
	@Override
	public Map getWillAgentByDomain(AgentInfoDomain domain) throws DataAccessException {
		Map<String, Object> map = new HashMap<String, Object>();
		AgentInfoModel agentInfoModel = new AgentInfoModel();
		agentInfoModel = MyBeanUtils.map(domain, AgentInfoModel.class);
		AgentInfoExample example = initWillAgentInfoExample(agentInfoModel);
		int pageBegin = (domain.getPageNum() - 1) * domain.getPageSize();
		List<AgentInfo> list = agentInfoDao.getPageByExample(domain.getPageSize(), pageBegin, example);
		List<AgentInfoModel> menuModelList = MyBeanUtils.map(list, AgentInfoModel.class);
		int count = agentInfoDao.countByExample(example);
		map.put("count", count);
		map.put("list", menuModelList);
		return map;
	}

	/**
	 * 新增代理商
	 * <p>
	 * 包括结算银行卡信息
	 * base_acct_info  在新增商户 新增代理的时候要记录一条
	 *
	 * @throws Exception
	 * @throws IOException
	 */
	// 如果有事务,那么加入事务,没有的话新建一个(不写的情况下)
	@Transactional(propagation = Propagation.REQUIRED)
	public String editAgentInfo(AgentSettleCardInfoModel model, AgentInfoModel curAgentInfoModel) throws IOException, Exception {
		AgentInfoModel agentInfoModel = model.getAgentInfoModel();
		if (StrUtils.isBlank(agentInfoModel.getAgentId())) {//新增
			saveAgentInfo(agentInfoModel, curAgentInfoModel);
		} else {//编辑
			updateAgentInfo(agentInfoModel, curAgentInfoModel);
		}

		return agentInfoModel.getAgentId();
	}


	/**
	 * 根据登录名查找对应的代理商
	 */
	public AgentInfoModel getAgentInfoModelBySysAccount(String sysAccount)
			throws DataAccessException {

		AgentInfoExample example = new AgentInfoExample();
		com.zx.map.dao.model.AgentInfoExample.Criteria criteria = example.createCriteria();
		criteria.andSysAccountEqualTo(sysAccount);
		List<AgentInfo> list = agentInfoDao.getListByExample(example);
		if (list != null && list.size() > 0) {
			AgentInfoModel model = new AgentInfoModel();
			BeanUtils.copyProperties(list.get(0), model);
			return model;
		}
		return null;

	}


	/**
	 * 查询bsid 对应的代理信息
	 *
	 * @return
	 */
	@Override
	public List<AgentInfo> queryAgentInfoByBsid(String bsid) {
		ArrayList<AgentInfo> agentInfoArrayList = new ArrayList<AgentInfo>();
		if (StrUtils.isEmpty(bsid)) {
			return agentInfoArrayList;
		}
		List<String> agentIdsList = Arrays.asList(bsid.split("-"));
		return queryAgentInfoByIdList(agentIdsList);
	}


	/**
	 * 查询agentIds 对应的代理信息
	 *
	 * @return
	 */
	@Override
	public List<AgentInfo> queryAgentInfoByIdList(List<String> agentIds) {
		ArrayList<AgentInfo> agentInfoArrayList = new ArrayList<AgentInfo>();
		if (agentIds == null || agentIds.isEmpty()) {
			return agentInfoArrayList;
		}
		AgentInfoExample agentInfoExample = new AgentInfoExample();
		AgentInfoExample.Criteria criteria = agentInfoExample.createCriteria();
		criteria.andAgentIdIn(agentIds);
		return agentInfoDao.getListByExample(agentInfoExample);
	}

	/**
	 * 转让代理
	 *
	 * @param curAgentInfoModel
	 * @param transAgentDomain
	 * @return
	 */
	public Map<String, Object> transAgent(AgentInfoModel curAgentInfoModel, TransAgentDomain transAgentDomain) {
		String fromAccount = transAgentDomain.getFromAccount();
		AgentInfoModel fromAgentInfoModel = getAgentInfoModelBySysAccount(fromAccount);
		if (fromAgentInfoModel == null) {
			return CommonResponseUtils.failureResponse("待转让代理不存在");
		}
		if (curAgentInfoModel == null || curAgentInfoModel.getAgentId().equals(fromAgentInfoModel.getParentAgentId())) {
		} else {
			return CommonResponseUtils.failureResponse("不是直属代理，不能转让");
		}
		String toAccount = transAgentDomain.getToAccount();
		AgentInfoModel toAgentInfoModel = getAgentInfoModelBySysAccount(toAccount);
		if (toAgentInfoModel == null) {
			return CommonResponseUtils.failureResponse("待接收代理不存在");
		}
		if (fromAgentInfoModel.getParentAgentId().equals(toAgentInfoModel.getAgentId())) {
			return CommonResponseUtils.failureResponse("已是直属代理，不需转让");
		}
		if (fromAgentInfoModel.getAgentLevel().compareTo(toAgentInfoModel.getAgentLevel()) <= 0) {
			return CommonResponseUtils.failureResponse("待接收代理级别过低！");
		}
		fromAgentInfoModel.setParentAgentId(toAgentInfoModel.getAgentId());
		fromAgentInfoModel.setUpdateDate(new Date());
		AgentInfo agentInfo = MyBeanUtils.map(fromAgentInfoModel, AgentInfo.class);
		agentInfoDao.update(agentInfo);
		this.updateAgentBelong(fromAgentInfoModel.getBsid(), toAgentInfoModel.getBsid() + "-" + fromAgentInfoModel.getAgentId());

		MerchantInfoModel merchantInfoModel = merchantInfoService.getMerchantInfoModelBySysAccount(agentInfo.getSysAccount());
		merchantInfoModel.setUpdateDate(new Date());
		merchantInfoModel.setAgentId(toAgentInfoModel.getAgentId());
		merchantInfoService.update(merchantInfoModel);

		return CommonResponseUtils.successResponse("转让成功");
	}


	/**
	 * 关闭代理
	 *
	 * @param agentInfoModel
	 * @param curAgentInfoModel
	 * @return
	 */
	public Map<String, Object> closeAgent(AgentInfoModel agentInfoModel, AgentInfoModel curAgentInfoModel) {
		String agentId = agentInfoModel.getAgentId();

		AgentInfoModel oldAgentInfoModel = this.getModelByKey(agentId);
		if (oldAgentInfoModel == null || StrUtils.isBlank(agentId) || oldAgentInfoModel == null) {
			return CommonResponseUtils.failureResponse("用户不存在");
		}

		//关闭  查看是否直属
		if (curAgentInfoModel == null || curAgentInfoModel.getAgentId().equals(oldAgentInfoModel.getParentAgentId())) {
		} else {
			return CommonResponseUtils.failureResponse("不是直属代理，不能关闭");
		}

		return updateAgentInfo(agentInfoModel, curAgentInfoModel);
	}

	/**
	 * 更新或新增
	 *
	 * @param agentInfoModel
	 * @param curAgentInfoModel
	 * @return
	 */
	@Override
	public Map<String, Object> saveOrUpdateAgentInfo(AgentInfoModel agentInfoModel, AgentInfoModel curAgentInfoModel) {
		String agentId = agentInfoModel.getAgentId();
		if (StrUtils.isBlank(agentId)) {
			//新增
			//检验登录名的唯一性
			return saveAgentInfo(agentInfoModel, curAgentInfoModel);
		} else {
			return updateAgentInfo(agentInfoModel, curAgentInfoModel);
		}

	}


	@Override
	public Map<String, Object> updateAgentInfo(AgentInfoModel newAgentInfoModel, AgentInfoModel curAgentInfoModel) {
		String agentId = newAgentInfoModel.getAgentId();

		AgentInfoModel oldAgentInfoModel = this.getModelByKey(agentId);
		if (oldAgentInfoModel == null || StrUtils.isBlank(agentId) || oldAgentInfoModel == null) {
			return CommonResponseUtils.failureResponse("用户不存在");
		}
		String oldLevel = oldAgentInfoModel.getAgentLevel();
		String newLevel = newAgentInfoModel.getAgentLevel();


		newAgentInfoModel.setSysAccount(oldAgentInfoModel.getSysAccount());
		if ("2".equals(newAgentInfoModel.getAgentType()) && StrUtils.isNotBlank(newAgentInfoModel.getCompanyShortName())) {//如果是企业代理  重新设置代理名称 方便查询统一查找
			newAgentInfoModel.setAgentName(newAgentInfoModel.getCompanyShortName());
		}

		boolean isChange = false;    //代理等级修改了，则重新设置角色


		if (!oldLevel.equals(newLevel)) {
			isChange = true;
			updateAgentLevel(curAgentInfoModel, newAgentInfoModel);
		}

		AgentInfo agentInfo = new AgentInfo();
		BeanUtils.copyProperties(newAgentInfoModel, agentInfo);
		agentInfoDao.update(agentInfo);

		//修改登录信息
		OperatorInfoModel operatorInfoModel = new OperatorInfoModel();
		operatorInfoModel.setLoginName(agentInfo.getSysAccount());
		//先查出操作人信息
		operatorInfoModel = operatorInfoService.getModelByAgentInfo(operatorInfoModel);
		if (null != operatorInfoModel) {
			//operatorInfoModel.setOperatorName(agentInfo.getCompanyName());
			//操作人名称应该是代理商名称edit by wenjw 2016.9.6
			operatorInfoModel.setOperatorName(agentInfo.getAgentName());
			//operatorInfoModel.setLoginName(agentInfo.getSysAccount());
			//operatorInfoModel.setLoginPassword(DesUtil.encrypt(agentInfo.getSysPassword(), null));
			//operatorInfoModel.setStatus("I");
			//操作员类型为代理人
			//int aLevel = Integer.valueOf(agentInfo.getAgentLevel());
			//operatorInfoModel.setOperatorType(String.valueOf(aLevel+1));
			//operatorInfoModel.setOperatorType("2");
			operatorInfoService.update(operatorInfoModel);
			//如果代理等级变化了，则修改代理商角色 edit by wenjw 2016.9.8
			if (isChange) {
				//设置代理商角色
				//operatorRolesModel.setRoleIds("4;");
				//agentInfo
				OperatorRolesModel operatorRolesModel = new OperatorRolesModel();
				operatorRolesModel.setOperatorId(operatorInfoModel.getOperatorId());
				String agentLevel = agentInfo.getAgentLevel();
				operatorRolesModel.setRoleIds(agentLevel + ";");

				operatorInfoService.setOperatorRoles(operatorRolesModel);
			}
		}
		return CommonResponseUtils.successResponse("修改成功");
	}

	/**
	 * 更改从属关系
	 *
	 * @param curAgentInfoModel
	 * @param newAgentInfoModel
	 * @return
	 */
	private String updateAgentLevel(AgentInfoModel curAgentInfoModel, AgentInfoModel newAgentInfoModel) {
		String agentId = newAgentInfoModel.getAgentId();
		AgentInfoModel oldAgentInfoModel = this.getModelByKey(agentId);

		int num = 0;
		String newLevel = newAgentInfoModel.getAgentLevel();
		String oldLevel = oldAgentInfoModel.getAgentLevel();
		//修改当前的bsid
		String parentBsidStr = null;
		String parentAgentId = null;
		if ((curAgentInfoModel == null || StrUtils.isBlank(curAgentInfoModel.getAgentId())) && newLevel.equals(SUConstants.AGENT_LEVEL_SUBCOMPANY)) {  //升级到分公司
			parentBsidStr = SUConstants.DEFAULT_AGENTID;
			parentAgentId = SUConstants.DEFAULT_AGENTID;
		} else if (curAgentInfoModel == null || StrUtils.isBlank(curAgentInfoModel.getAgentId())) {//如果当前操作人员没有关联的代理商则设置默认为上海宝数子公司  处理对子公司降级
			parentBsidStr = SUConstants.DEFAULT_AGENTID + "-" + SUConstants.DEFAULT_SUBAGENTID;
			parentAgentId = SUConstants.DEFAULT_SUBAGENTID;
		} else {
			parentBsidStr = curAgentInfoModel.getBsid();
			parentAgentId = curAgentInfoModel.getAgentId();
		}
		newAgentInfoModel.setParentAgentId(parentAgentId);
		newAgentInfoModel.setBsid(parentBsidStr + "-" + agentId);
		if (newLevel.compareTo(oldLevel) > 0) {//降级
			//2：更改发展的代理商归属 （1：大于等于修改后的新等级的直属代理商，2：小于新等级的代理商）

			//1: 查询等级大于等于新等级的直属代理商
			AgentInfoExample agentInfoExample = new AgentInfoExample();
			AgentInfoExample.Criteria criteria = agentInfoExample.createCriteria();
			criteria.andParentAgentIdEqualTo(agentId);
			if (newLevel.equals(SUConstants.AGENT_LEVEL_WILL)) {
				criteria.andAgentLevelLessThanOrEqualTo(SUConstants.AGENT_LEVEL_COMMON);
			} else {
				criteria.andAgentLevelLessThanOrEqualTo(newLevel);
			}
			List<AgentInfo> agentInfoList = agentInfoDao.getListByExample(agentInfoExample);  //必须放到更新的前面，否则找不到
			//归属到当前代理商
			AgentInfo temp = new AgentInfo();
			temp.setParentAgentId(parentAgentId);
			agentInfoDao.updateByExampleSelective(temp, agentInfoExample);
			//维护层级关系字段
			for (AgentInfo agentInfo : agentInfoList) {  //待修改的同级、上级的下级
				//把下下级代理归属上级 bsid
				num = this.updateAgentBelong(agentInfo.getBsid(), parentBsidStr + "-" + agentInfo.getAgentId());
				log.debug("更改代理从属数量:" + num + "   oldBsid:" + agentInfo.getBsid() + "  newBsid:" + parentBsidStr + "-" + agentInfo.getAgentId());
				MerchantInfoModel merchantInfoModel = merchantInfoService.getMerchantInfoModelBySysAccount(agentInfo.getSysAccount());
				merchantInfoModel.setUpdateDate(new Date());
				merchantInfoModel.setAgentId(parentAgentId);
				merchantInfoService.update(merchantInfoModel);
			}

		}
		//修改自己层级关系
		num = this.updateAgentBelong(oldAgentInfoModel.getBsid(), newAgentInfoModel.getBsid());
		log.debug("更改代理从属数量:" + num + "   oldBsid:" + oldAgentInfoModel.getBsid() + "  newBsid:" + newAgentInfoModel.getBsid());

		MerchantInfoModel merchantInfoModel = merchantInfoService.getMerchantInfoModelBySysAccount(oldAgentInfoModel.getSysAccount());
		merchantInfoModel.setUpdateDate(new Date());
		merchantInfoModel.setAgentId(parentAgentId);
		merchantInfoService.update(merchantInfoModel);
		return SUConstants.CODE_SUCCESS_VALUE;
	}

	/**
	 * 获取直属下级 且级别高于或等于代理商新级别
	 *
	 * @param agentId
	 * @param newLevel
	 * @return
	 */
	private List<AgentInfo> queryDirectAgent_LevelLessThanOrEquelTo(String agentId, int newLevel) {
		AgentInfoExample agentInfoExample = new AgentInfoExample();
		AgentInfoExample.Criteria criteria = agentInfoExample.createCriteria();
		criteria.andParentAgentIdEqualTo(agentId);
		criteria.andAgentLevelLessThanOrEqualTo("" + newLevel);
		return agentInfoDao.getListByExample(agentInfoExample);
	}

	/**
	 * 更新代理商从属关系
	 *
	 * @param fromBsid
	 * @param toBsid
	 * @return
	 */
	@Override
	public int updateAgentBelong(String fromBsid, String toBsid) {
		return agentInfoDao.updateAgentBelong(fromBsid, toBsid);
	}

	/**
	 * 根据model  查询符合条件的代理商信息
	 *
	 * @param model
	 * @return
	 */
	@Override
	public List<AgentInfoModel> queryAgentInfoJustByModel(AgentInfoModel model) {
		AgentInfoExample example = new AgentInfoExample();
		example = initSearchAgentInfo(example, model);
		List<AgentInfo> agentInfoList = agentInfoDao.getListByExample(example);
		List<AgentInfoModel> agentInfoModelList = MyBeanUtils.map(agentInfoList, AgentInfoModel.class);
		return agentInfoModelList;
	}

	/**
	 * 校验唯一性
	 */
	public List checkSingle(AgentInfoModel model) throws DataAccessException {
		return queryAgentInfoJustByModel(model);
	}

	/**
	 * 保存
	 *
	 * @param agentInfoModel
	 * @param curAgentInfoModel
	 * @return
	 */
	@Override
	public Map<String, Object> saveAgentInfo(AgentInfoModel agentInfoModel, AgentInfoModel curAgentInfoModel) {
		OperatorInfoModel operatorInfoModel = new OperatorInfoModel();
		operatorInfoModel.setLoginName(agentInfoModel.getSysAccount());
		List<OperatorInfoModel> operatorInfoModelList = operatorInfoService
				.checkSingle(operatorInfoModel);
		if (operatorInfoModelList != null
				&& operatorInfoModelList.size() > 0) {
			return CommonResponseUtils.failureResponse("账号已存在,保存失败");
		} else {

			if ((curAgentInfoModel == null || StrUtils.isBlank(curAgentInfoModel.getAgentId())) && agentInfoModel.getAgentLevel().equals(SUConstants.AGENT_LEVEL_SUBCOMPANY)) {  //开分公司
				agentInfoModel.setParentAgentId(SUConstants.DEFAULT_AGENTID);
				agentInfoModel.setBsid(SUConstants.DEFAULT_AGENTID);
			} else if (curAgentInfoModel == null || StrUtils.isBlank(curAgentInfoModel.getAgentId())) {//如果当前操作人员没有关联的代理商则设置默认为上海宝数子公司
				agentInfoModel.setParentAgentId(SUConstants.DEFAULT_SUBAGENTID);
				agentInfoModel.setBsid(SUConstants.DEFAULT_AGENTID + "-" + SUConstants.DEFAULT_SUBAGENTID);
			} else {
				agentInfoModel.setParentAgentId(curAgentInfoModel.getAgentId());
				agentInfoModel.setBsid(curAgentInfoModel.getBsid());
			}
			if ("2".equals(agentInfoModel.getAgentType())) {//如果是企业代理  重新设置代理名称 方便查询统一查找
				agentInfoModel.setAgentName(agentInfoModel.getCompanyShortName());
			}

			AgentInfo agentInfo = new AgentInfo();
			BeanUtils.copyProperties(agentInfoModel, agentInfo);
			String agentId = agentInfoDao.add(agentInfo);
			agentInfoModel.setAgentId(agentId);
			//新增登录信息
			operatorInfoModel = new OperatorInfoModel();
			//operatorInfoModel.setOperatorName(agentInfo.getCompanyName());
			//操作人名称应该是代理商名称edit by wenjw 2016.9.6
			operatorInfoModel.setOperatorName(agentInfo.getAgentName());
			operatorInfoModel.setLoginName(agentInfo.getSysAccount());
			String pwd = agentInfo.getSysPassword();
			try {
				if (StrUtils.isBlank(pwd)) {
					pwd = SUConstants.DEFAULT_PWD;
				}
				pwd = DesUtil.encrypt(pwd, null);
			} catch (Exception e) {
			}
			operatorInfoModel.setLoginPassword(pwd);
			operatorInfoModel.setStatus("I");
			//操作员类型为代理人
			//operatorInfoModel.setOperatorType("2");
			int aLevel = Integer.valueOf(agentInfo.getAgentLevel());
			operatorInfoModel.setOperatorType(String.valueOf(aLevel + 1));
			operatorInfoModel.setRoleId(aLevel);
			String operatorId = operatorInfoService.add(operatorInfoModel);
			//新增客户信息
//			BaseAcctInfoModel baseAcctInfoModel = new BaseAcctInfoModel();
//			baseAcctInfoModel.setCustId(agentId);//设置成主键一致，从而保持关联
//			baseAcctInfoModel.setCustType("2");
//			baseAcctInfoModel.setAcctStatus("N");
//			baseAcctInfoModel.setAcctType("B");
//			baseAcctInfoModel.setCreateDate(new Date());
			//设置初始角色
			OperatorRolesModel operatorRolesModel = new OperatorRolesModel();
			operatorRolesModel.setOperatorId(operatorId);
			//设置代理商角色
			//operatorRolesModel.setRoleIds("4;");
			//agentInfo
			String agentLevel = agentInfo.getAgentLevel();
			operatorRolesModel.setRoleIds(agentLevel + ";");

			operatorInfoService.setOperatorRoles(operatorRolesModel);
			//baseAcctInfoService.add(baseAcctInfoModel);
		}
		return CommonResponseUtils.successResponse("保存成功");
	}


	// * 获取本下、下级代理商id   查询深度根据当前用户角色判断    平台账号查询全部
	@Override
	public List<String> queryDownAgentIdList(AgentInfoModel curAgentInfoModel) {
		return queryDownAgentIdList(curAgentInfoModel, null);
	}

	/**
	 * 1.根据当前用户查询所有下级代理商
	 * 2.根据下级代理商集合id，和查找条件，再次筛选查询下级
	 * 3.根据当前的用户层级，查找下级的代理商id
	 *
	 * @param curAgentInfoModel
	 * @param searchAgentInfoModel
	 * @return
	 */
	@Override
	public List<String> queryDownAgentIdList(AgentInfoModel curAgentInfoModel, AgentInfoModel searchAgentInfoModel) {
		List<String> agentIds = queryDownAgentIdListBySearchAgentInfo(curAgentInfoModel, searchAgentInfoModel);
		return agentIds;
	}

	/**
	 * * 获取本下、下级代理商信息   查询深度根据当前用户角色判断     平台账号查询全部
	 */
	@Override
	public List<AgentInfoModel> queryDownAgentInfoList(AgentInfoModel curAgentInfoModel) {
		return queryDownAgentInfoList(curAgentInfoModel, null);
	}

	/**
	 * 1.根据当前用户查询所有下级代理商
	 * 2.根据下级代理商集合id，和查找条件，再次筛选查询下级
	 * 3.根据当前的用户层级，查找下级的代理商model
	 *
	 * @param curAgentInfoModel
	 * @param searchAgentInfoModel
	 * @return
	 */
	@Override
	public List<AgentInfoModel> queryDownAgentInfoList(AgentInfoModel curAgentInfoModel, AgentInfoModel searchAgentInfoModel) {

		List<AgentInfo> agentInfoList = queryListAgentInfoBySearchAgentInfo(curAgentInfoModel, searchAgentInfoModel);
		return converteAgentModel(agentInfoList, curAgentInfoModel);
	}

	/**
	 * 转换成model
	 *
	 * @param agentInfoList
	 * @param curAgentInfoModel
	 * @return
	 */
	private List<AgentInfoModel> converteAgentModel(List<AgentInfo> agentInfoList, AgentInfoModel curAgentInfoModel) {
		List<AgentInfoModel> values = new ArrayList<AgentInfoModel>();
/*		int parentLengh=0;
		if(curAgentInfoModel!=null&&StrUtils.isNotBlank(curAgentInfoModel.getBsid())){
			parentLengh=curAgentInfoModel.getBsid().split("-").length;
		}
		int deep=getSearchDeep(curAgentInfoModel);*/

		if (agentInfoList != null && agentInfoList.size() > 0) {
			for (int i = 0; i < agentInfoList.size(); i++) {
				AgentInfo m = agentInfoList.get(i);
				if (StrUtils.isBlank(m.getBsid())) {
					continue;
				}
				AgentInfoModel agentInfoModel = new AgentInfoModel();
				MyBeanUtils.map(m, agentInfoModel);
				values.add(agentInfoModel);

			/*	int lengh= m.getBsid().split("-").length;
				//比较bsid的长度
				if(deep==-1){
					values.add(agentInfoModel);
				} else if (lengh-parentLengh<=deep) {
					values.add(agentInfoModel);
				}*/
			}
		}
		return values;
	}


	/**
	 * 转换agentInfo 按当前用户层级 获取下级代理商的id
	 *
	 * @param agentInfoList
	 * @param curAgentInfoModel
	 * @return
	 */
	private List<String> converteAgentId(List<AgentInfo> agentInfoList, AgentInfoModel curAgentInfoModel) {
		List<String> values = new ArrayList<String>();
/*		int parentLengh=0;
		if(curAgentInfoModel!=null&&StrUtils.isNotBlank(curAgentInfoModel.getBsid())){
			parentLengh=curAgentInfoModel.getBsid().split("-").length;
		}
		int deep=getSearchDeep(curAgentInfoModel);*/

		if (agentInfoList != null && agentInfoList.size() > 0) {
			for (int i = 0; i < agentInfoList.size(); i++) {
				AgentInfo m = agentInfoList.get(i);
				if (StrUtils.isBlank(m.getBsid())) {
					continue;
				}
				values.add(m.getAgentId());
				/*int lengh= m.getBsid().split("-").length;
				//比较bsid的长度
				if(deep==-1){
					values.add(m.getAgentId());
				} else if (lengh-parentLengh<=deep) {
					values.add(m.getAgentId());
				}*/

			}
		}
		return values;
	}

	private int getSearchDeep(AgentInfoModel curAgentInfoModel) {
		int deep = 1;
		if (curAgentInfoModel == null || StrUtils.isBlank(curAgentInfoModel.getAgentId())) {
			deep = -1;
		} else {
			//查询层级
			String level = curAgentInfoModel.getAgentLevel();
			if (SUConstants.AGENT_LEVEL_SUBCOMPANY.equals(level)) {
				deep = 2;
			} else if (SUConstants.AGENT_LEVEL_SUPER.equals(level)) {
				deep = 1;
			} else {
				deep = 0;
			}
		}
		return deep;
	}

	private List<AgentInfo> queryListAgentInfoBySearchAgentInfo(AgentInfoModel curAgentInfoModel, AgentInfoModel searchAgentInfoModel) {

		AgentInfoExample example = initAgentInfoExample(curAgentInfoModel, searchAgentInfoModel);
		return agentInfoDao.getListByExample(example);
	}
	//查询下级代理id集合
	private List<String> queryDownAgentIdListBySearchAgentInfo(AgentInfoModel curAgentInfoModel, AgentInfoModel searchAgentInfoModel) {

		AgentInfoExample example = initAgentInfoExample(curAgentInfoModel, searchAgentInfoModel);
		return agentInfoDao.getDownAgentIdList(example);
	}

	private AgentInfoExample initAgentInfoExample(AgentInfoModel curAgentInfoModel, AgentInfoModel searchAgentInfoModel) {

		AgentInfoExample example = new AgentInfoExample();
		AgentInfoExample.Criteria criteria = example.createCriteria();

		if (curAgentInfoModel != null && StringUtils.isNotBlank(curAgentInfoModel.getAgentId())) {
			criteria.andBsidLike("%" + curAgentInfoModel.getAgentId() + "%");
			if (!curAgentInfoModel.isHasSelf()) {//不包括自己
				criteria.andAgentIdNotEqualTo(curAgentInfoModel.getAgentId());
			}
			criteria.andAgentLevelBetween(curAgentInfoModel.getAgentLevel(), SUConstants.AGENT_LEVEL_COMMON);//不适合总代进入查询，用平台去查
		}

		example = initSearchAgentInfo(example, searchAgentInfoModel);
		return example;
	}

	private AgentInfoExample initSearchAgentInfo(AgentInfoExample example, AgentInfoModel searchAgentInfoModel) {
		List<AgentInfoExample.Criteria> criteriaList = example.getOredCriteria();
		AgentInfoExample.Criteria criteria = criteriaList.isEmpty() ? example.createCriteria() : criteriaList.get(0);
		if (searchAgentInfoModel != null) {

			if (StringUtils.isNotBlank(searchAgentInfoModel.getSysAccount())) {
				criteria.andSysAccountLike("%" + searchAgentInfoModel.getSysAccount() + "%");
			} else {
				criteria.andSysAccountLike("1%");
			}
			if (StringUtils.isNotBlank(searchAgentInfoModel.getAgentName())) {
				criteria.andAgentNameLike("%" + searchAgentInfoModel.getAgentName() + "%");
			}
			if (StrUtils.isNotBlank(searchAgentInfoModel.getAgentId())) {
				criteria.andAgentIdEqualTo(searchAgentInfoModel.getAgentId());
			}
			if (StringUtils.isNotBlank(searchAgentInfoModel.getAgentLevel())) {
				criteria.andAgentLevelEqualTo(searchAgentInfoModel.getAgentLevel());
			}
			if (StringUtils.isNotBlank(searchAgentInfoModel.getAgentType())) {
				criteria.andAgentTypeEqualTo(searchAgentInfoModel.getAgentType());
			}
			if (StringUtils.isNotBlank(searchAgentInfoModel.getBussContact())) {
				criteria.andBussContactLike("%" + searchAgentInfoModel.getBussContact() + "%");
			}
			if (StrUtils.isNotBlank(searchAgentInfoModel.getCompanyName())) {
				criteria.andCompanyNameLike("%" + searchAgentInfoModel.getCompanyName() + "%");
			}
			if (StrUtils.isNotBlank(searchAgentInfoModel.getIdentityNo())) {
				criteria.andIdentityNoEqualTo(searchAgentInfoModel.getIdentityNo());
			}
			if (StrUtils.isNotBlank(searchAgentInfoModel.getMobilephone())) {
				criteria.andMobilephoneEqualTo(searchAgentInfoModel.getMobilephone());
			}
			if (StrUtils.isNotBlank(searchAgentInfoModel.getParentAgentId())) {
				criteria.andParentAgentIdEqualTo(searchAgentInfoModel.getParentAgentId());
			}
			if (StringUtils.isNotBlank(searchAgentInfoModel.getBeginDate())) {
				if(StringUtils.isNotBlank(searchAgentInfoModel.getEndDate())) {
					criteria.andCreateDateBetween(PmpUtils.strToDate(searchAgentInfoModel.getBeginDate(), "yyyy-MM-dd"),
							PmpUtils.addDate(PmpUtils.strToDate(searchAgentInfoModel.getEndDate(), "yyyy-MM-dd"), 1));
				}else {
					criteria.andCreateDateGreaterThanOrEqualTo(PmpUtils.strToDate(searchAgentInfoModel.getBeginDate(), "yyyy-MM-dd"));
				}
				
			}else if(StringUtils.isNotBlank(searchAgentInfoModel.getEndDate())) {
				criteria.andCreateDateLessThanOrEqualTo(PmpUtils.addDate(PmpUtils.strToDate(searchAgentInfoModel.getEndDate(), "yyyy-MM-dd"), 1));
			}

			if (StringUtils.isNotBlank(searchAgentInfoModel.getIsOverDate())) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Date nowDate = new Date();
				String nowDates = format.format(nowDate);
				//获取当前月第一天
				Calendar c = Calendar.getInstance();
				c.add(Calendar.MONTH, 0);
				c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
				String first = format.format(c.getTime());
				//获取当前月最后一天
				Calendar ca = Calendar.getInstance();
				ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
				String last = format.format(ca.getTime());
				if (searchAgentInfoModel.getIsOverDate().equals("1")) {
					criteria.andBussEnddateBetween(first, last);
				} else if (searchAgentInfoModel.getIsOverDate().equals("2")) {
					criteria.andBussEnddateLessThan(nowDates);
				}
			}
		} else {
			criteria.andSysAccountLike("1%");
		}
		example.setOrderByClause("CREATE_DATE desc");
		return example;
	}

	private AgentInfoExample initWillAgentInfoExample(AgentInfoModel agentInfoModel) {
		AgentInfoExample example = new AgentInfoExample();
		AgentInfoExample.Criteria criteria = example.createCriteria();
		if (agentInfoModel != null) {
			if (StringUtils.isNotBlank(agentInfoModel.getSysAccount())) {
				criteria.andSysAccountLike("%" + agentInfoModel.getSysAccount() + "%");
			} else {
				criteria.andSysAccountLike("1%");
			}
			if (StringUtils.isNotBlank(agentInfoModel.getAgentName())) {
				criteria.andAgentNameLike("%" + agentInfoModel.getAgentName() + "%");
			}
			if (StringUtils.isNotBlank(agentInfoModel.getAgentLevel())) {
				criteria.andAgentLevelEqualTo(agentInfoModel.getAgentLevel());
			}
			if (StrUtils.isNotBlank(agentInfoModel.getParentAgentId())) {
				criteria.andParentAgentIdEqualTo(agentInfoModel.getParentAgentId());
			}
			if (StringUtils.isNotBlank(agentInfoModel.getBeginDate())) {
				criteria.andCreateDateBetween(PmpUtils.strToDate(agentInfoModel.getBeginDate(), "yyyy-MM-dd"),
						PmpUtils.addDate(PmpUtils.strToDate(agentInfoModel.getEndDate(), "yyyy-MM-dd"), 1));
			}
		} else {
			criteria.andSysAccountLike("1%");
		}
		example.setOrderByClause("CREATE_DATE desc");
		return example;
	}

}
